<template>
  <div>
    <el-row :gutter="10" class="mb8">
      <!-- 账期操作 -->
      <div>
        <el-col v-hasPermi="['system:clientManger:saveModel']" :span="1.5">
          <el-button
            type="primary"
            @click="handleAdd"
          >
            新增
          </el-button>
        </el-col>
      </div>
    </el-row>
    <el-table
      v-loading="loading"
      :data="tableData"
      max-height="400px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="结算模式" prop="settlementModel" :formatter="formatterSettlementMode"></el-table-column>
      <el-table-column label="授信额度" prop="lineCredit"></el-table-column>
      <el-table-column label="预充值额度" prop="preloaded"></el-table-column>
      <el-table-column label="已用额度" prop="amountUsed"></el-table-column>
      <el-table-column label="未结算账单" prop="dateUser"></el-table-column>
      <el-table-column label="账单付款天数" prop="billPaymentDay"></el-table-column>
      <el-table-column
        label="操作"
        min-width="100"
        fixed="right"
        align="center"
      >
        <template #default="{row}">
          <el-button
            v-hasPermi="['system:clientManger:editModel']"
            type="primary"
            text
            @click="() => editHandle(row)"
          >
            修改
          </el-button>
          <el-button
            v-hasPermi="['system:clientManger:deleteModel']"
            type="danger"
            text
            @click="handleDel(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增，修改 -->
    <el-dialog
      v-model="open"
      :title="title"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="FormRef"
        :rules="rules"
        :model="form"
        inline
        label-width="110px"
      >
        <el-form-item label="结算模式" prop="settlementModel">
          <el-select
            v-model="form.settlementModel"
            placeholder="请选择结算模式"
            clearable
            style="width: 180px;"
          >
            <el-option
              v-for="dict in dicts[DictDirection.客户结算模式]"
              :key="dict.dictLabel"
              placeholder="请选择结算模式"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授信额度" prop="lineCredit">
          <el-input-number
            v-model="form.lineCredit"
            style="width: 180px;"
           
            :controls="false"
            clearable
            placeholder="请输入授信额度"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="预充值额度" prop="preloaded">
          <el-input-number
            v-model="form.preloaded"
            style="width: 180px;"
            :controls="false"
            clearable
            placeholder="预充值额度"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="账单付款天数" prop="billPaymentDay">
          <el-input-number
            v-model="form.billPaymentDay"
            style="width: 180px;"
            :controls="false"
            clearable
            placeholder="请输入账单付款天数"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>   
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, watchEffect } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import userDicts, { DictDirection } from '@/store/modules/dicts'
import { accountPeriodList, accountPeriodDetail, updateAccountPeriod, deleteAccountPeriod, addAccountPeriod } from '@/api/customer/accountPeriodData'
import { validateForm } from '@/utils/index'

const dicts = userDicts()
const loading = ref(false)
const tableData = ref([{}])
const ids = ref([])

// const formatterSettlementMode = (row) => {
//   const obj = dicts[DictDirection.客户结算模式].find(item => item.dictValue === row.settlementModel)
//   return obj && obj.dictLabel
// }
const formatterSettlementMode = (row) => dicts.getDictLabel({ dict: DictDirection.客户结算模式, value: row.settlementModel })as string
/* 新增，修改账期 */
const props = defineProps({
  productId: {
    type: Number,
  },
})

const open = ref(false)
const idss = ref(null)
const form = ref({
  customerId: props.productId,
  settlementModel: '',
  lineCredit: 0,
  preloaded: 0,
  billPaymentDay: 0,
})
const rules = ref({
  settlementModel: [{ required: true, message: '结算模式不能为空', trigger: ['blur', 'change'] }],
  lineCredit: [{ required: true, message: '授信额度不能为空', trigger: ['blur', 'change'] }],
  preloaded: [{ required: true, message: '预充值额度不能为空', trigger: ['blur', 'change'] }],
  billPaymentDay: [{ required: true, message: '付款天数不能为空', trigger: ['blur', 'change'] }],
})
const title = ref('')
const FormRef = ref(null)
const handleSelectionChange = (rows) => {
  ids.value = rows.map(item => item.id) 
}

const getList = () => {
  if (!props.productId) return
  loading.value = true
  const data = { customerId: props.productId,
    pageSize: 10,
    pageNum: 1,
  }
  accountPeriodList(data).then(res => {
    if (res.code === 200) {
      tableData.value = res.data || []
    }
  }).finally(() => {
    loading.value = false
  })
}
// 新增修改——确定
const submit = () => {
  validateForm(FormRef.value, () => {
    let msg = ''
    let response = null
    if (form.value.id != undefined) {
      response = updateAccountPeriod(form.value)
    } else {
      msg = '新增成功'
      response = addAccountPeriod(form.value)
    }
    response
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success(msg)
        open.value = false
        getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
    .catch((error) => {
      ElMessage.error(error)
    })
  })
}
const handleDel = (row) => {
  const rowList = JSON.parse(JSON.stringify(row))
  const id = rowList.id || ids

  ElMessageBox.confirm(
    `"是否确认删除客户编号为"${ id }"的数据项?"`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
  .then(() => deleteAccountPeriod(id))
  .then((res) => {
    if (res.code === 200) {
      getList(id)
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.error(error)
    }
  })
}
const editHandle = (row) => {
  open.value = true
  accountPeriodDetail(row.id)
  .then((res) => {
    if (res.code === 200) {
      form.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((err) => {
    console.log(err)
    ElMessage.error(err)
  })
}
const cancel = () => {
  open.value = false
  FormRef.value.resetFields()
}
const handleAdd = () => {
  console.log('1')
  open.value = true
}
defineExpose({
  idss,
})
// 初始化
watchEffect(getList)
</script>